<template>
  <div class="material">
    <el-drawer
      v-model="drawerMaterial"
      title="手动选取素材"
      size="55%"
      class="native-anchor-drawer"
      direction="rtl"
      @close="handleDrawerClose(false)"
    >
      <div class="material-content">
        <div class="material-content-item">
          <el-form :model="form" label-width="160px" label-position="left" :rules="rules" ref="formRef">
            <el-form-item label="多账户分配规则" prop="myMaterialType">
              <el-radio-group v-model="myMaterialType" @change="handleMyMaterialTypeChange">
                <el-radio-button label="1">
                  <span>全账户复用</span>
                  <span>所有账户都使用一样的素材</span>
                </el-radio-button>
                <!-- <el-radio-button label="2">
                  <span>平均分配</span>
                  <span>素材平均分到每个账户中</span>
                </el-radio-button> -->
                <el-radio-button label="3">
                  <span>分账户选择</span>
                  <span>每个账户单独选择素材</span>
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="区分素材版式" prop="materialLayout ">
              <el-radio-group v-model="materialLayout">
                <el-radio-button label="1"> 不启用</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item prop="videoNumberTotal" class="creative-group-item">
              <template #label>
                <span>每个创意组配置</span>
                <el-icon style="cursor: pointer" title="创意组的素材配置，即为广告内的创意形式；创意组数量，影响广告最终生成数量。">
                  <QuestionFilled />
                </el-icon>
              </template>
              <div class="creative-group">
                <el-input
                  v-model="videoTotals"
                  type="number"
                  maxlength="30"
                  :max="30"
                  placeholder="请输入"
                  @blur="handleVideoNumberTotalBlur"
                  @keydown.enter.native="handleVideoNumberTotalBlur"
                >
                  <template #prepend>视频</template>
                </el-input>
                <p>注：因媒体限制，视频最多30个</p>
                <!-- <el-input v-model="form.name" placeholder="请输入">
                  <template #prepend>图片</template>
                </el-input>
                <el-input v-model="form.name" placeholder="请输入">
                  <template #prepend>图文</template>
                </el-input> -->
              </div>
            </el-form-item>
            <el-form-item prop="name">
              <template #label>
                <span>引导视频</span>
                <el-icon style="cursor: pointer" title="媒体白名单功能，仅游戏行业广告主投放奖励关卡广告时必填">
                  <QuestionFilled />
                </el-icon>
              </template>
              <el-radio-group v-model="guideVideo">
                <el-radio-button label="1"> 不启用</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="myMaterialType == '1'">
              <template #label>
                <span>批量添加</span>
              </template>
              <div class="btnbox">
                <div class="w-[100px] cursor-pointer h-[40px] flex justify-center items-center adbox" @click="addMaterialLibrary(-1)">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </div>
              </div>
            </el-form-item>
            <div class="text-[12px] flex items-baseline text-[#999] tips" v-if="myMaterialType == '1'">
              创意组数量 (<span class="text-[#409EFF]">{{ groupQos.length }}</span
              >)
              <div class="ml-[20px] cursor-pointer clearbtn text-[#409EFF]" @click="clearAll">清空</div>

              <div class="ml-[20px] cursor-pointer clearbtn text-[#409EFF]" @click="sortRandomAll">打乱顺序</div>
            </div>
          </el-form>
          <div class="creative-group-list">
            <!-- 复用 -->
            <div v-if="myMaterialType == '1'">
              <template v-for="(item, index) in groupQos" :key="index">
                <el-tabs
                  class="creative-group-list-tabs"
                  style="margin-bottom: 20px"
                  type="border-card"
                  addable
                  :class="item.isFold ? 'active' : ''"
                  v-if="item.advertiserId == form.selectAccountId || myMaterialType != '3'"
                >
                  <template #add-icon>
                    <el-icon @click="handleWhetherToFold(3, index)">
                      <DocumentCopy />
                    </el-icon>
                    <el-icon @click="handleWhetherToFold(1, index)" v-if="!item.isFold">
                      <CaretBottom />
                    </el-icon>
                    <el-icon @click="handleWhetherToFold(2, index)" v-else>
                      <CaretTop />
                    </el-icon>
                    <el-icon @click="delCreativeGroup(index)">
                      <Delete />
                    </el-icon>
                  </template>
                  <el-tab-pane :label="item.name">
                    <el-tabs type="card" v-model="form.fileType">
                      <el-tab-pane :label="'视频(' + item.videoMaterialList.length + '/' + form.videoNumberTotal + ')'" name="video">
                        <div class="creative-group-list-item">
                          <div class="add-creative-box">
                            <div class="item-creative-group" v-for="(itm, idx) in item.videoMaterialList" :key="idx">
                              <img :src="form.fileType == 'imgage' ? itm.url : itm.posterUrl" alt="" />
                              <el-icon @click="delImg(index, idx)">
                                <CircleCloseFilled />
                              </el-icon>
                            </div>
                            <div class="add-creative-group" @click="addMaterialLibrary(index)" v-if="item.videoMaterialList.length < videoTotals">
                              <el-icon>
                                <Plus />
                              </el-icon>
                            </div>
                          </div>
                        </div>
                      </el-tab-pane>
                      <!-- <el-tab-pane :label="'图片(' + 0 + '/' + 0 + ')'" name="image">
                      <div class="creative-group-list-item"></div>
                    </el-tab-pane> -->
                    </el-tabs>
                  </el-tab-pane>
                </el-tabs>
              </template>
              <el-button type="primary" @click="addCreativeGroup">添加创意组</el-button>
            </div>
            <!-- 分账户 -->
            <el-tabs v-model="form.selectAccountId" v-if="myMaterialType == '3'" @tab-change="handleSelectAccountIdChange">
              <el-tab-pane v-for="(accountItm, accountIdx) in myAccountList" :key="accountIdx" :label="accountItm?.name" :name="accountItm?.id">
                <div>
                  <div class="btnbox">
                    <!-- class="w-[100px] cursor-pointer h-[40px] flex justify-center items-center adbox" -->
                    <!-- @click="addAccountMaterialLibrary(accountItm, -1)" -->
                    <div class="">
                      <!-- 批量添加<el-icon><Plus /></el-icon> -->
                      <el-button type="primary" plain @click="addAccountMaterialLibrary(accountItm, -1)">
                        <span class="text-[12px]">批量添加</span>
                        <el-icon>
                          <Plus />
                        </el-icon>
                      </el-button>
                    </div>
                  </div>
                  <div class="text-[12px] flex items-baseline text-[#999] tips pt-[10px] pb-[10px]">
                    创意组数量 (<span class="text-[#409EFF]">{{ accountItm.accountGroupQos.length }}</span
                    >)
                    <div class="ml-[20px] cursor-pointer clearbtn text-[#409EFF]" @click="clearAccountGroupQosAll(accountItm.id)">清空</div>

                    <div class="ml-[20px] cursor-pointer clearbtn text-[#409EFF]" @click="sortRandomAll">打乱顺序</div>
                  </div>
                  <template v-for="(item, index) in accountItm.accountGroupQos" :key="index">
                    <el-tabs
                      class="creative-group-list-tabs"
                      style="margin-bottom: 20px"
                      type="border-card"
                      addable
                      :class="item.isFold ? 'active' : ''"
                    >
                      <template #add-icon>
                        <el-icon @click="handleWhetherToFold(3, index)">
                          <DocumentCopy />
                        </el-icon>
                        <el-icon @click="handleWhetherToFold(1, index)" v-if="!item.isFold">
                          <CaretBottom />
                        </el-icon>
                        <el-icon @click="handleWhetherToFold(2, index)" v-else>
                          <CaretTop />
                        </el-icon>
                        <el-icon @click="delCreativeGroup(index)">
                          <Delete />
                        </el-icon>
                      </template>
                      <el-tab-pane :label="item.name">
                        <el-tabs type="card" v-model="form.fileType">
                          <el-tab-pane :label="'视频(' + item.videoMaterialList.length + '/' + form.videoNumberTotal + ')'" name="video">
                            <div class="creative-group-list-item">
                              <div class="add-creative-box">
                                <div class="item-creative-group" v-for="(itm, idx) in item.videoMaterialList" :key="idx">
                                  <img :src="form.fileType == 'imgage' ? itm.url : itm.posterUrl" alt="" />
                                  <el-icon @click="delImg(index, idx)">
                                    <CircleCloseFilled />
                                  </el-icon>
                                </div>
                                <div
                                  class="add-creative-group"
                                  @click="addAccountMaterialLibrary(accountItm, index)"
                                  v-if="item.videoMaterialList.length < videoTotals"
                                >
                                  <el-icon>
                                    <Plus />
                                  </el-icon>
                                </div>
                              </div>
                            </div>
                          </el-tab-pane>
                          <!-- <el-tab-pane :label="'图片(' + 0 + '/' + 0 + ')'" name="image">
                        <div class="creative-group-list-item"></div>
                      </el-tab-pane> -->
                        </el-tabs>
                      </el-tab-pane>
                    </el-tabs>
                  </template>
                  <el-button type="primary" @click="addCreativeGroup">添加创意组</el-button>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDrawerClose(false)">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </template>
    </el-drawer>
  </div>

  <MaterialLibrary
    :isMaterialLibrary="isMaterialLibrary"
    @update:isMaterialLibrary="updateIsMaterialLibrary"
    :fileType="form.fileType"
    :groupQos="groupQos"
    @selectedRows="getSelectedRows"
    :selectedVioIndex="selectedVioIndex"
    :videoTotals="videoTotals"
    :userList="props.userList"
    @updateGroup="updateSingleGroup"
    :selectAdvertiserId="selectAdvertiserId"
    @updateSelectAdvertiserId="getSelectAdvertiserId"
    :mySelectAccountGroupQos="mySelectAccountGroupQos"
    :myMaterialType="myMaterialType"
    :selectedAccountIndex="selectedAccountIndex"
    @selectAccountGroupQos="getSelectAccountGroupQos"
  />
</template>

<script setup lang="ts">
const drawerMaterial = ref(false);
import { triggerRef } from 'vue';
import { useAppStore } from '@/store/modules/app';
import { confirmPromote, deepClone } from '@/utils/index';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps(['drawerMaterial', 'accountList', 'userList', 'groupQos', 'mySelectAccounts', 'myMaterialType']);
const emit = defineEmits(['update:drawerMaterial', 'selectedRows', 'selectAccounts', 'materialType']);
const appStore = useAppStore();
// const selectedRows = ref([]);
const selectedVioIndex = ref('0');
const selectedAccountIndex = ref('0');
const isMaterialLibrary = ref(false);
const myMaterialType = ref('1'); // 1:单素材 2:多素材 3:多素材多账户
const materialLayout = ref('1'); //区分素材版式
// const assignCreativeGroup = ref('1'); //是否分配创意组
const creativeGroupsNumber = ref('1'); //创意组数量
// const videosNumber = ref(null); //视频数量
const creativeGroupName = ref('1'); //统一配置创意组名
const guideVideo = ref('1'); // 引导视频
const videoTotals = ref(1); // 视频总数
const newGroupQos = ref([]);
const selectAdvertiserId = ref(''); // 选中的账户id
const mySelectAccountGroupQos = ref([]); // 选中的账户列表
const initFormData: any = {
  type: '',
  fileType: 'video', // 文件类型
  videoNumberTotal: '1', // 视频数量总数
  selectAccountId: '', // 选中账户id
  activeName: '',
  activeName1: 'first'
};
const data = reactive({
  form: { ...initFormData },
  groupQos: [
    {
      name: '创意组1',
      materialType: '1',
      // advertiserId: '',
      isFold: false, //是否折叠
      videoMaterialList: [],
      videoTotals: 1
    }
  ],
  myAccountList: [
    {
      id: '',
      name: '',
      accountGroupQos: [
        {
          name: '创意组1',
          materialType: '1',
          // advertiserId: '',
          isFold: false, //是否折叠
          videoMaterialList: [],
          videoTotals: 1
        }
      ]
    }
  ],
  rules: {
    name: [{ required: true, message: '请输入素材名称', trigger: 'blur' }],
    type: [{ required: true, message: '请选择素材类型', trigger: 'change' }]
  }
});

const { form, queryParams, rules, groupQos, myAccountList } = toRefs(data);

const clearAll = async () => {
  let hasInfo = false;
  groupQos.value.map((item) => {
    if (hasInfo) return;
    if (item.videoMaterialList.length) {
      hasInfo = true;
    }
  });
  if (!hasInfo) {
    proxy?.$modal.msgError('没有可清除的数据');
    return;
  }

  await confirmPromote({ 'content': '确认清除所有吗？' });
  groupQos.value = [
    {
      name: '创意组1',
      materialType: '1',
      // advertiserId: '',
      isFold: false, //是否折叠
      videoMaterialList: [],
      videoTotals: videoTotals.value
    }
  ];
};
const clearAccountGroupQosAll = async (id) => {
  let hasInfo = false;
  myAccountList.value.map(async (item) => {
    if (item.id == id) {
      item.accountGroupQos.map((item) => {
        if (hasInfo) return;
        if (item.videoMaterialList.length) {
          hasInfo = true;
        }
      });
      if (!hasInfo) {
        proxy?.$modal.msgError('没有可清除的数据');
        return;
      }
      await confirmPromote({ 'content': '确认清除所有吗？' });
      item.accountGroupQos = [
        {
          name: '创意组1',
          materialType: '1',
          // advertiserId: '',
          isFold: false, //是否折叠
          videoMaterialList: [],
          videoTotals: videoTotals.value
        }
      ];
    }
  });
};

onMounted(() => {
  drawerMaterial.value = props.drawerMaterial;
  myAccountList.value = JSON.parse(JSON.stringify(props.userList));
  form.value.selectAccountId = props.userList[0]?.id; //默认选中第一个账户
  myAccountList.value.map((item) => {
    item.accountGroupQos = [
      {
        name: '创意组1',
        materialType: '1',
        // advertiserId: '',
        isFold: false, //是否折叠
        videoMaterialList: [],
        videoTotals: videoTotals.value
      }
    ];
  });
  console.log(myAccountList.value, 'myAccountList.value');
});

// 获取单个账户里面的所有创意组
const getSelectAccountGroupQos = (val) => {
  myAccountList.value.map((item) => {
    if (item.id == selectAdvertiserId.value) {
      item.accountGroupQos = val;
    }
  });
};
// 创意配置数量
const handleVideoNumberTotalBlur = (val) => {
  videoTotals.value = videoTotals.value > 30 ? 30 : videoTotals.value;
  if (myMaterialType.value == '3') {
    myAccountList.value.map((item) => {
      if (item.id == selectAdvertiserId.value) {
        if (item.accountGroupQos.length == 1 && item.accountGroupQos[0].videoMaterialList.length == 0) {
          form.value.videoNumberTotal = videoTotals.value;
          return;
        }
      }
    });
  } else {
    if (groupQos.value.length == 1 && groupQos.value[0].videoMaterialList.length == 0) {
      form.value.videoNumberTotal = videoTotals.value;
      return;
    }
  }
  // 弹窗提示是否确定修改数量
  ElMessageBox.confirm('确定修改该数量吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      form.value.videoNumberTotal = videoTotals.value;
      // 首选把所有的视频拿出来，然后重新分配
      let allVideoMaterialList = [];
      if (myMaterialType.value == '1') {
        groupQos.value.forEach((item) => {
          allVideoMaterialList.push(...item.videoMaterialList);
        });
      } else {
        myAccountList.value.forEach((item) => {
          if (item.id == selectAdvertiserId.value) {
            item.accountGroupQos.forEach((item) => {
              console.log(item, 'item');
              allVideoMaterialList.push(...item.videoMaterialList);
            });
          }
        });
      }
      console.log(allVideoMaterialList, 'allVideoMaterialList');

      //如果allVideoMaterialList的长度大于videoTotals.value，就开始根据videoTotals.value的数量对allVideoMaterialList进行平均分配到创意组groupQos.value中
      if (allVideoMaterialList.length > videoTotals.value) {
        let num = allVideoMaterialList.length / videoTotals.value; //创意组数量
        let remainder = allVideoMaterialList.length % videoTotals.value; //剩下不够分配的视频数量
        let newGroupQos = [];
        // 根据num的数量进行循环新增groupQos的创意组个数
        for (let i = 0; i < num; i++) {
          newGroupQos.push({
            name: '创意组' + (i + 1),
            materialType: myMaterialType.value,
            advertiserId: form.value.selectAccountId, //账户id
            isFold: false, //是否折叠
            videoMaterialList: []
          });
        }
        // 然后把所有的视频allVideoMaterialList根据videoTotals.value这个数量进行平均分配到newGroupQos的videoMaterialList中
        newGroupQos.map((item) => {
          item.videoMaterialList = allVideoMaterialList.splice(0, videoTotals.value);
        });
        // 如果remainder > 0，就把剩下的视频分配到newGroupQos的最后一个videoMaterialList中
        if (remainder > 0) {
          newGroupQos[newGroupQos.length - 1].videoMaterialList.push(...allVideoMaterialList);
        }
        if (myMaterialType.value == '3') {
          myAccountList.value.map((item) => {
            if (item.id == selectAdvertiserId.value) {
              item.accountGroupQos = newGroupQos;
            }
          });
        } else {
          groupQos.value = newGroupQos;
        }
      } else if (allVideoMaterialList.length <= videoTotals.value) {
        // 如果allVideoMaterialList长度小于videoTotals.value,就说明只有一条创意组，其余的就删掉，第一条把所有的视频都放进去
        if (myMaterialType.value == '3') {
          myAccountList.value.map((item) => {
            if (item.id == selectAdvertiserId.value) {
              item.accountGroupQos = [
                {
                  name: '创意组1',
                  materialType: myMaterialType.value,
                  advertiserId: form.value.selectAccountId, //账户id
                  isFold: false, //是否折叠
                  videoMaterialList: allVideoMaterialList
                }
              ];
            }
          });
        } else {
          groupQos.value = [
            {
              name: '创意组1',
              materialType: myMaterialType.value,
              advertiserId: form.value.selectAccountId, //账户id
              isFold: false, //是否折叠
              videoMaterialList: allVideoMaterialList
            }
          ];
        }
      }
    })
    .catch(() => {
      videoTotals.value = form.value.videoNumberTotal;
    });
};
// 是否分配创意组
const handleAssignCreativeGroupChange = (val) => {
  if (val == 1) {
    groupQos.value = [
      {
        name: '创意组1',
        materialType: myMaterialType.value,
        advertiserId: form.value.selectAccountId, //账户id
        isFold: false, //是否折叠
        videoMaterialList: []
      }
    ];
  }
};
// 输入创意组数量
const handleCreativeGroupsNumberBlur = (val) => {
  groupQos.value = [
    {
      name: '创意组1',
      materialType: myMaterialType.value,
      advertiserId: form.value.selectAccountId, //账户id
      isFold: false, //是否折叠
      videoMaterialList: []
    }
  ];
  console.log(creativeGroupsNumber.value, 'val');

  if (creativeGroupsNumber.value == null || creativeGroupsNumber.value == '' || creativeGroupsNumber.value < 1) {
    ElMessage({
      message: '创意组数量最小为1',
      type: 'warning'
    });
    creativeGroupsNumber.value = '1';
    return;
  }
  ElMessageBox.confirm('确定分配创意组数量吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {})
    .catch(() => {
      creativeGroupsNumber.value = null;
    });
};
//
const handleVideosNumberBlur = (val) => {
  ElMessageBox.confirm('确定分配视频数量吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      // 如果创意组数量是10，groupQos新增10个对象
      for (let i = 0; i < creativeGroupsNumber.value - 1; i++) {
        groupQos.value.push({
          name: '创意组' + (groupQos.value.length + 1),
          materialType: myMaterialType.value,
          advertiserId: form.value.selectAccountId, //账户id
          isFold: false, //是否折叠
          videoMaterialList: []
        });
      }
    })
    .catch(() => {
      creativeGroupsNumber.value = null;
    });
};
const handleSelectAccountIdChange = (val) => {
  console.log(val, 'newGroupQos');
  console.log(myAccountList.value, 'myAccountList');
  selectAdvertiserId.value = val;
};
//
const getSelectAdvertiserId = (val) => {
  console.log(val, 'SelectAdvertiserId');
  selectAdvertiserId.value = val;
};
const updateSingleGroup = (val) => {
  console.log(val, 'val');

  if (myMaterialType.value == '3') {
    // 使用深拷贝确保响应式更新
    console.log(myAccountList.value, 'myAccountList.value');

    myAccountList.value.map((item) => {
      if (selectAdvertiserId.value == item.id) {
        console.log(selectAdvertiserId.value, item.id, 'item');
        item.accountGroupQos = JSON.parse(JSON.stringify(val));
      }
    });
    // 强制触发视图更新（可选）
    nextTick(() => {
      console.log('更新后的myAccountList:', myAccountList.value);
    });
  } else {
    groupQos.value = val;
  }
};
// 提交
const submit = () => {
  emit('materialType', myMaterialType.value);
  if (myMaterialType.value == '3') {
    let selectAccounts = JSON.parse(JSON.stringify(myAccountList.value));
    selectAccounts.map((item) => {
      item.accountGroupQos.map((subitem) => {
        subitem.advertiserId = item.id; //账户id
      });
    });
    console.log(selectAccounts, 'selectAccountGroupQos');
    let newAccountGroupQos = [];
    selectAccounts.forEach((item) => {
      newAccountGroupQos.push(...item.accountGroupQos);
    });
    // newAccountGroupQos里面的videoMaterialList为空的筛掉
    newAccountGroupQos = newAccountGroupQos.filter((item) => item.videoMaterialList.length > 0);
    console.log(newAccountGroupQos, 'newAccountGroupQos');
    const data = newAccountGroupQos.map((item) => {
      let temp = {
        name: '',
        materialType: null,
        advertiserId: item.advertiserId, //账户id
        isFold: false, //是否折叠
        videoMaterialList: null,
        videoTotals: videoTotals.value
      };
      temp.advertiserId = item.advertiserId;
      temp.name = item.name;
      temp.videoMaterialList = item.videoMaterialList.map((subitem) => {
        // const regex = /tos-cn-p-0051\/[^\?]+~/;
        const regex = /tos-cn-p-[^?]+~/;
        const match = subitem.posterUrl.match(regex);
        return {
          imageMode: 'VIDEO_VERTICAL',
          videoId: subitem.id || subitem.videoId,
          videoCoverId: match ? match[0].replace('~', '') : '',
          videoHpVisibility: 'HIDE_VIDEO_ON_HP',
          posterUrl: subitem.posterUrl
        };
      });
      return temp;
    });
    emit('selectedRows', data);
    emit('selectAccounts', selectAccounts);
  } else {
    newGroupQos.value = groupQos.value;
    newGroupQos.value.map((item) => {
      delete item.isFold;
    });
    //组装数据
    const data = newGroupQos.value.map((item) => {
      let temp = {
        name: '',
        materialType: null,
        advertiserId: props.userList && props.userList[0].id, //账户id
        isFold: false, //是否折叠
        videoMaterialList: null,
        videoTotals: videoTotals.value
      };
      temp.advertiserId = props.userList && props.userList[0].id;
      temp.name = item.name;
      temp.videoMaterialList = item.videoMaterialList.map((subitem) => {
        // const regex = /tos-cn-p-0051\/[^\?]+~/;
        const regex = /tos-cn-p-[^?]+~/;
        const match = subitem.posterUrl.match(regex);
        return {
          imageMode: 'VIDEO_VERTICAL',
          videoId: subitem.id || subitem.videoId,
          videoCoverId: match ? match[0].replace('~', '') : '',
          videoHpVisibility: 'HIDE_VIDEO_ON_HP',
          posterUrl: subitem.posterUrl
        };
      });
      return temp;
    });
    console.log('===============>', data);
    emit('selectedRows', data);
  }

  handleDrawerClose(false);
};
//
const handleMyMaterialTypeChange = (val) => {
  console.log(val, 'val');
  if (val == 3) {
    form.value.selectAccountId = props.userList[0]?.id; //默认选中第一个账户
    groupQos.value = [
      {
        name: '创意组1',
        materialType: '1',
        // advertiserId: '',
        isFold: false, //是否折叠
        videoMaterialList: [],
        videoTotals: 1
      }
    ];
    selectAdvertiserId.value = props.userList[0].id; //默认选中第一个账户
  } else {
    myAccountList.value.map((item) => {
      item.accountGroupQos = [
        {
          name: '创意组1',
          materialType: '1',
          // advertiserId: '',
          isFold: false, //是否折叠
          videoMaterialList: [],
          videoTotals: 1
        }
      ];
    });
  }
};
// 新增创意组
const addCreativeGroup = () => {
  if (myMaterialType.value == '3') {
    myAccountList.value.map((item) => {
      if (item.id == selectAdvertiserId.value) {
        item.accountGroupQos.push({
          name: '创意组' + (item.accountGroupQos.length + 1),
          isFold: false, //是否折叠
          materialType: myMaterialType.value,
          videoMaterialList: [],
          videoTotals: videoTotals.value
        });
      }
    });
  } else {
    groupQos.value.push({
      name: '创意组' + (groupQos.value.length + 1),
      isFold: false, //是否折叠
      materialType: myMaterialType.value,
      videoMaterialList: []
    });
  }
};
const addAccountCreativeGroup = () => {};
const handleWhetherToFold = (type, index) => {
  if (myMaterialType.value == '3') {
    myAccountList.value.map((item) => {
      if (item.id == selectAdvertiserId.value) {
        if (type == 1) {
          item.accountGroupQos[index].isFold = true;
        } else if (type == 3) {
          // 复制
          item.accountGroupQos.push({
            ...deepClone(item.accountGroupQos[index]),
            name: '创意组' + (item.accountGroupQos.length + 1),
            isFold: false //是否折叠
          });
        } else {
          item.accountGroupQos[index].isFold = false;
        }
      }
    });
  } else {
    if (type == 1) {
      groupQos.value[index].isFold = true;
    } else if (type == 3) {
      //复制一个创意组
      groupQos.value.push({
        name: '创意组' + (groupQos.value.length + 1),
        isFold: false, //是否折叠
        materialType: myMaterialType.value,
        videoMaterialList: deepClone(groupQos.value[index].videoMaterialList)
      });
    } else {
      groupQos.value[index].isFold = false;
    }
  }
};
const getSelectedRows = (val: any) => {
  // groupQos.value[selectedVioIndex.value].videoMaterialList.push(...val);
  // // 去重
  // groupQos.value[selectedVioIndex.value].videoMaterialList = groupQos.value[selectedVioIndex.value].videoMaterialList.reduce((prev, cur) => {
  //   const idx = prev.findIndex((item) => item.id == cur.id);
  //   if (idx < 0) {
  //     prev.push(cur);
  //   }
  //   return prev;
  // }, []);
  // // 如果输入videoTotals.value，
  // isMaterialLibrary.value = false;
  if (myMaterialType.value == '3') {
    myAccountList.value.map((item) => {
      if (item.id == selectAdvertiserId.value) {
        console.log(val, 'val66666');

        if (val.length <= item.accountGroupQos) {
          item.accountGroupQos.map((itm, idx) => {
            itm.videoMaterialList = val[idx];
          });
        } else {
          val.map((itms, idxs) => {
            if (idxs < item.accountGroupQos.length) {
              item.accountGroupQos[idxs].videoMaterialList = val[idxs];
            } else {
              item.accountGroupQos.push({
                name: '创意组' + (idxs + 1),
                isFold: true, //是否折叠
                materialType: myMaterialType.value,
                videoMaterialList: val[idxs],
                videoTotals: Number(videoTotals.value)
              });
            }
          });
        }
        console.log(myAccountList.value, 'myAccountList.value');
      }
    });
  } else {
    if (val.length <= groupQos.value) {
      groupQos.value.map((item, index) => {
        item.videoMaterialList = val[index];
      });
    } else {
      val.map((item, index) => {
        if (index < groupQos.value.length) {
          groupQos.value[index].videoMaterialList = val[index];
        } else {
          groupQos.value.push({
            name: '创意组' + (index + 1),
            isFold: true, //是否折叠
            materialType: myMaterialType.value,
            videoMaterialList: val[index],
            videoTotals: Number(videoTotals.value)
          });
        }
      });
    }
  }
  isMaterialLibrary.value = false;
};
const handleDrawerClose = (val: boolean) => {
  drawerMaterial.value = val;
  emit('update:drawerMaterial', val);
};
const updateIsMaterialLibrary = (val: boolean) => {
  isMaterialLibrary.value = val;
};
const delCreativeGroup = (index: number) => {
  if (myMaterialType.value == '3') {
    myAccountList.value.map((item) => {
      if (item.id == selectAdvertiserId.value) {
        if (item.accountGroupQos.length == 1) {
          ElMessage({
            message: '至少保留一个创意组',
            type: 'warning'
          });
          return;
        }
      }
    });
  } else {
    if (groupQos.value.length == 1) {
      ElMessage({
        message: '至少保留一个创意组',
        type: 'warning'
      });
      return;
    }
  }
  // 提示是否删除
  ElMessageBox.confirm('确定删除创意组' + (index + 1) + '吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    if (myMaterialType.value == '3') {
      myAccountList.value.map((item) => {
        if (item.id == selectAdvertiserId.value) {
          item.accountGroupQos.splice(index, 1);
          item.accountGroupQos.map((itms, idxs) => {
            itms.name = '创意组' + (idxs + 1);
          })
        }
      });
    } else {
      groupQos.value.splice(index, 1);
    }
    groupQosResetSort();
  });
};

const groupQosResetSort = () => {
  groupQos.value.map((item, index) => {
    item.name = '创意组' + (index + 1);
    if (index === 0) {
      item.isFold = false;
    } else {
      item.isFold = true;
    }
  });
};

const delImg = (index: number, idx: number) => {
  if (myMaterialType.value == '3') {
    myAccountList.value.map((item) => {
      if (item.id == selectAdvertiserId.value) {
        item.accountGroupQos[index].videoMaterialList.splice(idx, 1);
      }
    });
  } else {
    groupQos.value[index].videoMaterialList.splice(idx, 1);
  }
};
const addMaterialLibrary = (index) => {
  console.log('index131241', index);
  if (
    creativeGroupsNumber.value == '0' ||
    creativeGroupsNumber.value == null ||
    creativeGroupsNumber.value == undefined ||
    creativeGroupsNumber.value == ''
  ) {
    ElMessage({
      message: '请先输入分配创意组数量',
      type: 'warning'
    });
    return;
  }
  if (videoTotals.value == 0 || videoTotals.value == null || videoTotals.value == undefined || videoTotals.value == '') {
    ElMessage({
      message: '请先输入分配视频数量',
      type: 'warning'
    });
    return;
  }
  selectedVioIndex.value = index;
  if (index !== -1) {
    if (groupQos.value[index].videoMaterialList.length >= form.value.videoNumberTotal) {
      ElMessage({
        message: '最多添加' + form.value.videoNumberTotal + '个素材',
        type: 'warning'
      });
      return;
    }
  }

  isMaterialLibrary.value = true;
};
const addAccountMaterialLibrary = (accountItm, index) => {
  mySelectAccountGroupQos.value = accountItm.accountGroupQos;
  selectedAccountIndex.value = index;
  isMaterialLibrary.value = true;
};

/**
 *全部账户复用乱序
 * */
const sortRandomAll = () => {
  //

  if (myMaterialType.value == '3') {
    myAccountList.value.map((item) => {
      if (item.id == selectAdvertiserId.value) {
        // item.accountGroupQos.push({
        //   name: '创意组' + (item.accountGroupQos.length + 1),
        //   isFold: false, //是否折叠
        //   materialType: myMaterialType.value,
        //   videoMaterialList: [],
        //   videoTotals: videoTotals.value
        // });
        item.accountGroupQos.sort(() => {
          return Math.random() - 0.5;
        });
        item.accountGroupQos.forEach((item, index) => {
          item.name = `创意组${index + 1}`;
        });
      }
    });
  } else {
    groupQos.value.sort(() => {
      return Math.random() - 0.5;
    });
    groupQos.value.forEach((item, index) => {
      item.name = `创意组${index + 1}`;
    });
  }
};

watch(
  () => props.drawerMaterial,
  (val) => {
    drawerMaterial.value = val;
    // 分账户不回显
    // if (props.mySelectAccounts) {
    //   myAccountList.value.map((item, index) => {
    //     props.mySelectAccounts.forEach((item1) => {
    //       if (item.id == item1.id) {
    //         item.accountGroupQos = item1.accountGroupQos;
    //       }
    //     });
    //   });
    // }
    myMaterialType.value = props.myMaterialType ? String(props.myMaterialType) : '1';
    console.log('myMaterialType.value', myMaterialType.value);

    form.value.selectAccountId = props.userList[0]?.id; //默认选中第一个账户
    if (props.myMaterialType == '3') {
      groupQos.value = [
        {
          name: '创意组1',
          materialType: '1',
          // advertiserId: '',
          isFold: false, //是否折叠
          videoMaterialList: [],
          videoTotals: 1
        }
      ];
    } else {
      myAccountList.value.map((item) => {
        item.accountGroupQos = [
          {
            name: '创意组1',
            materialType: '1',
            // advertiserId: '',
            isFold: false, //是否折叠
            videoMaterialList: [],
            videoTotals: 1
          }
        ];
      });
      nextTick(() => {
        if (props.groupQos) {
          groupQos.value = props.groupQos;
        }
        videoTotals.value = props.groupQos
          ? props.groupQos[0].videoTotals
            ? props.groupQos[0].videoTotals
            : props.groupQos[0].videoMaterialList.length
          : 1;
        form.value.videoNumberTotal = videoTotals.value;
        console.log('videoTotals.va888lue', props.groupQos, videoTotals.value);
      });
    }
    console.log(myAccountList.value, 'myAccountList.value');
  },
  {
    immediate: true
  }
);
watch(
  () => props.groupQos,
  () => {
    nextTick(() => {
      groupQos.value = props.groupQos;
      videoTotals.value = props.groupQos
        ? props.groupQos[0].videoTotals
          ? props.groupQos[0].videoTotals
          : props.groupQos[0].videoMaterialList.length
        : 1;
      form.value.videoNumberTotal = videoTotals.value;
      console.log('videoTotals.value', props.groupQos, videoTotals.value);
    });
  }
);
</script>

<style scoped lang="scss">
.material {
  .material-content {
    padding: 0 20px;

    .material-content-item {
      .el-radio-group {
        :deep(.el-radio-button__inner) {
          display: flex;
          flex-direction: column;
        }

        span {
          display: block;

          &:first-child {
            font-size: 14px;
            font-weight: 600;
            padding-bottom: 10px;
          }

          &:last-child {
            font-size: 12px;
          }
        }
      }

      .creative-group-item {
        width: 70%;

        .creative-group {
          display: flex;
          // justify-content: space-ar;
          align-items: center;

          .el-input {
            margin-right: 40px;
            width: 50%;
          }
        }
      }

      .group-name-item {
        .creative-group-name {
          display: flex;
          align-items: center;

          .el-input {
            width: 70%;
          }

          .el-button {
            margin-left: 10px;
          }
        }
      }
    }

    .creative-group-list {
      margin-top: 20px;

      .creative-group-list-tabs {
        :deep(.el-tabs__new-tab) {
          margin-right: 20px;
          justify-content: space-around !important;
          width: 80px;
          font-size: 16px;
          border: none;
          cursor: pointer;
        }

        :deep(.el-tabs__new-tab:hover) {
          color: inherit;
        }
      }

      .creative-group-list-tabs.active {
        :deep(.el-tabs__content) {
          display: none;
        }
      }

      .creative-group-list-item {
        min-height: 400px;

        .add-creative-box {
          width: 100%;
          display: flex;
          flex-wrap: wrap;
          //   flex-direction: column;
          //   justify-content: center;
          //   align-items: center;
          width: 100%;
          height: 100%;

          .add-creative-group {
            margin: 10px;
            width: 120px;
            height: 160px;
            border: 1px dashed #ccc;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 24px;
            color: #ccc;
            cursor: pointer;
          }

          .item-creative-group {
            position: relative;
            margin: 10px;
            width: 120px;
            height: 160px;

            img {
              width: 100%;
              height: 100%;
              cursor: pointer;
            }

            .el-icon {
              cursor: pointer;
              position: absolute;
              top: -10px;
              right: -10px;
              font-size: 15px;
            }
          }
        }
      }
    }
  }
}

.adbox {
  border: 1px dashed #ccc;
  border-radius: 4px;
}
</style>
